<template>
	<view class="comment-area-container">
		<!-- 评论区 -->
		<view class="comment-area">
			<view class="count">共 {{ getCommentListLength }} 条评论</view>
			<view class="comment-bar" @click="showCommentPopup = true">
				<image :src="userData.avatarUrl" class="app-avatar"></image>
				<view class="bar">留下你的想法吧...</view>
			</view>
			<!-- 无评论 -->
			<view v-if="commentList.length === 0" class="empty">
				<u-empty mode="data" text="暂无评论，快来发布第一条评论吧！"> </u-empty>
			</view>
			<!-- 有评论 -->
			<view v-else class="comment-list">
				<view v-for="item in commentList" :key="item.id">
					<!-- 一级评论 -->
					<CommentItem :commentData="item" @press="handleLongPress(item)" @viewImage="handleViewImage" />
					<!-- 二级评论 -->
					<CommentItem
						v-for="child in item.children"
						:key="child.id"
						:commentData="child"
						:isSecond="true"
						@press="handleLongPress(child)"
						@viewImage="handleViewImage"
					/>
				</view>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="footer-bar">
			<view class="user" @click="showCommentPopup = true">
				<image :src="userData.avatarUrl" class="app-avatar"></image>
				<view class="bar"> 说点什么... </view>
			</view>
			<view class="bar-item" @click="handleLike">
				<u-icon :name="getLikeIconStyle.icon" :color="getLikeIconStyle.color" size="28" :label="post.likes ? post.likes : 0"></u-icon>
			</view>
			<view class="bar-item" @click="handleCollect">
				<u-icon :name="getCollectIconStyle.icon" :color="getCollectIconStyle.color" size="28" :label="post.collect ? post.collect : 0"></u-icon>
			</view>
			<view class="bar-item" @click="showCommentPopup = true">
				<u-icon name="chat" size="28" :label="commentList.length"></u-icon>
			</view>
		</view>
		<view class="placeholder"></view>

		<!-- 评论弹出层 -->
		<Popup :show="showCommentPopup" @close="closeCommentPopup">
			<view class="input-bar">
				<view class="input-bar-tips">发送评论</view>
				<view class="picture-wrapper">
					<view v-for="item in imageList" :key="item" class="picture-item">
						<image :src="item" mode="scaleToFill" />
						<view class="delete">
							<u-icon name="close-circle" size="14" color="#666" @click="handleDeleteImage"></u-icon>
						</view>
					</view>
				</view>
				<view class="textarea">
					<u--textarea v-model="commentContent" :placeholder="commentPlaceholder" autoHeight></u--textarea>
				</view>
				<view class="btn-list">
					<u-icon name="photo" size="28" color="#666" @click="handleChooseImage"></u-icon>
					<view class="submit" @click="handleSubmitComment">发送</view>
				</view>
			</view>
		</Popup>

		<!-- 长按评论弹出操作栏 -->
		<Popup :show="showOperationPopup" @close="closeOperationPopup">
			<view class="operation-bar">
				<view class="cell"> @{{ operatingComment.userVO.nickname }}: {{ operatingComment.content }} </view>
				<view class="cell" @click="handleReply"> 回复 </view>
				<view class="cell" @click="handleCopy"> 复制 </view>
				<view class="cell" @click="handleDelete"> 删除 </view>
				<view class="cell" @click="showOperationPopup = false"> 取消 </view>
			</view>
		</Popup>
	</view>
</template>

<script>
import Popup from '@/components/Popup/Popup.vue';
import CommentItem from './CommentItem.vue';
import request from '@/api/http.js';
import { baseurl } from '@/api/http.js';

export default {
	components: {
		Popup,
		CommentItem
	},
	props: {
		post: {
			type: Object,
			default: () => {
				return {
					likes: 0,
					collect: 0,
					liked: false,
					collected: false
				};
			}
		},
		commentList: {
			type: Array,
			default: () => {
				return [];
			}
		},
		userData: {
			type: Object,
			default: () => {
				return {};
			}
		}
	},
	computed: {
		commentPlaceholder() {
			let placeholder = '发表你的看法吧...';
			if (this.operatingComment.content) {
				placeholder = `回复@${this.operatingComment.userVO.nickname}: ${this.operatingComment.content}`;
			}
			return placeholder;
		},
		getLikeIconStyle() {
			const likeStyle = {
				color: this.themeColor,
				icon: 'thumb-up-fill'
			};
			const dislikeStyle = {
				color: '#333',
				icon: 'thumb-up'
			};
			return this.post.liked ? likeStyle : dislikeStyle;
		},
		getCollectIconStyle() {
			const collectStyle = {
				color: '#FFC107',
				icon: 'star-fill'
			};
			const notCollectStyle = {
				color: '#333',
				icon: 'star'
			};
			return this.post.collected ? collectStyle : notCollectStyle;
		},
		getCommentListLength() {
			let sum = this.commentList.length;
			this.commentList.forEach(item => {
				sum += item.children.length;
			});
			return sum;
		}
	},
	data() {
		return {
			showCommentPopup: false,
			operatingComment: {},
			commentContent: '',
			showOperationPopup: false,
			defaultSignature: '这个人很懒，什么都没有留下',
			imageList: [],
			obsUrl: '' // 上传到华为云OBS的图片URL
		};
	},
	methods: {
		handleLongPress(item) {
			// 长按评论弹出操作栏
			this.showOperationPopup = true;
			this.operatingComment = item;
			console.log(item);
		},
		handleReply() {
			// 回复评论
			this.showOperationPopup = false;
			setTimeout(() => {
				console.log('this.operatingComment=====>', this.operatingComment);
				let comment = {
					type: 0, // 0: 帖子评论 1: 桌游评论 2:活动评论
					postId: this.post.id, // 帖子id
					repliedCommentId: this.operatingComment.id, // 这条评论回复的 评论id
					fatherId: this.operatingComment ? (this.operatingComment.fatherId ? this.operatingComment.fatherId : this.operatingComment.id) : null, // 父评论（一级评论）id
					receiverId: this.operatingComment.userId ?? this.post.userId // 评论接收者的用户id
				};
				console.log('comment=====>', comment);
				this.showCommentPopup = true;
			}, 300);
		},
		handleCopy() {
			// 复制评论
			uni.setClipboardData({
				data: this.operatingComment.content,
				success: () => {
					uni.showToast({
						title: '复制成功',
						icon: 'none'
					});
				}
			});
			this.showOperationPopup = false;
		},
		handleDelete() {
			// 删除评论
		},
		closeCommentPopup() {
			// 关闭评论弹出层
			this.showCommentPopup = false;
			this.operatingComment = {};
		},
		closeOperationPopup() {
			// 关闭操作评论弹出层
			this.showOperationPopup = false;
			this.operatingComment = {
				userVO: {
					nickname: ''
				},
				content: ''
			};
		},
		async handleSubmitComment() {
			let comment = {
				type: 0, // 0: 帖子评论 1: 桌游评论 2:活动评论
				postId: this.post.id, // 帖子id
				repliedCommentId: this.operatingComment.id, // 这条评论回复的 评论id
				fatherId: this.operatingComment ? (this.operatingComment.fatherId ? this.operatingComment.fatherId : this.operatingComment.id) : null, // 父评论（一级评论）id
				receiverId: this.operatingComment.userId ?? this.post.userId, // 评论接收者的用户id
				content: this.commentContent, // 评论内容
				url: this.obsUrl // 图片地址
			};
			// 提交评论
			this.$emit('submitComment', comment);
			this.commentContent = '';
			this.obsUrl = '';
			this.closeCommentPopup();
		},
		async handleLike() {
			// 点赞
			this.$emit('like');
		},
		async handleCollect() {
			// 收藏
			this.$emit('collect');
		},
		async handleDelete() {
			let res = await request(`/comments/delete?postId=${this.post.id}&commentId=${this.operatingComment.id}`);
			this.closeOperationPopup();
			this.$emit('delete');
			if (res.data.code == 200) {
				uni.showToast({
					title: '删除成功',
					icon: 'none'
				});
			} else if (res.data.code == 3000) {
				uni.showToast({
					title: '删除失败，无权限操作',
					icon: 'none'
				});
			} else {
				uni.showToast({
					title: '删除失败，请稍后再试',
					icon: 'none'
				});
			}
		},
		handleChooseImage() {
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					this.imageList = res.tempFilePaths;
					this.handleUploadImage();
				}
			});
		},
		handleUploadImage() {
			const token = uni.getStorageSync('token');
			const userId = uni.getStorageSync('userId');
			uni.uploadFile({
				url: `${baseurl}/comments/uploadImage`,
				filePath: this.imageList[0],
				name: 'file',
				header: {
					authentication: token,
					id: userId
				},
				success: (res) => {
					const url = JSON.parse(res.data).data;
					this.obsUrl = url;
				}
			});
		},
		handleDeleteImage() {
			this.imageList = [];
			this.obsUrl = '';
		},
		// 查看图片
		handleViewImage(url) {
			uni.previewImage({urls: [url]});
		}
	}
};
</script>

<style lang="scss">
.comment-area-container {
	width: 750rpx;

	.comment-area {
		display: flex;
		flex-direction: column;
		width: calc(100% - 40rpx);
		padding: 20rpx;

		.count {
			font-size: $font-size-small;
			color: #999;
			margin-top: 20rpx;
		}

		.comment-bar {
			display: flex;
			margin-top: 20rpx;

			.bar {
				font-size: $font-size-small;
				color: #999;
				background-color: #eee;
				width: 400rpx;
				display: flex;
				align-items: center;
				padding: 0 30rpx;
				border-radius: 50rpx;
				height: 60rpx;
			}
		}

		.empty {
			margin-top: 40rpx;
		}

		.comment-list {
			width: 100%;
			display: flex;
			flex-direction: column;
		}
	}

	.footer-bar {
		position: fixed;
		z-index: 10;
		bottom: 0;
		left: 0;
		right: 0;
		width: 700rpx;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-around;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		padding: 0 25rpx;
		animation: popup 0.3s ease-in-out;

		@keyframes popup {
			0% {
				transform: translateY(100%);
			}

			100% {
				transform: translateY(0);
			}
		}

		.user {
			display: flex;

			.bar {
				font-size: $font-size-small;
				color: #999;
				background-color: #eee;
				width: 200rpx;
				display: flex;
				align-items: center;
				padding: 0 30rpx;
				border-radius: 50rpx;
				height: 60rpx;
			}
		}

		.bar-item {
			display: flex;
		}

		@keyframes thumb-up {
			0% {
				transform: scale(1) rotate(0deg);
			}

			50% {
				transform: scale(0.8) rotate(10deg);
			}

			75% {
				transform: scale(1.2) rotate(-20deg);
			}

			100% {
				transform: scale(1) rotate(0deg);
			}
		}

		.uicon-thumb-up-fill {
			animation: thumb-up 1s ease-in-out;
			transition: color 0.5s ease-in-out;
		}

		@keyframes collect {
			0% {
				transform: scale(1);
			}

			50% {
				transform: scale(0.8);
			}

			75% {
				transform: scale(1.2);
			}

			100% {
				transform: scale(1);
			}
		}

		.uicon-star-fill {
			animation: collect 1s ease-in-out;
			transition: color 0.5s ease-in-out;
		}
	}

	.placeholder {
		width: 750rpx;
		height: 100rpx;
	}

	.input-bar {
		display: flex;
		flex-direction: column;
		margin: 20rpx 0;
		height: max-content;

		.input-bar-tips {
			font-size: $font-size-base;
			color: #999;
			margin: 0 20rpx;
			margin-bottom: 20rpx;
			text-align: center;
		}

		.picture-wrapper {
			display: flex;
			flex-wrap: wrap;
			justify-content: flex-start;
			align-items: center;
			margin: 0 20rpx;

			.picture-item {
				width: 150rpx;
				height: 150rpx;
				margin-right: 20rpx;
				margin-bottom: 20rpx;
				position: relative;
				border-radius: 10rpx;
				overflow: hidden;

				image {
					width: 100%;
					height: 100%;
					border-radius: 10rpx;
					object-fit: cover;
				}

				.delete {
					position: absolute;
					right: 10rpx;
					top: 10rpx;
				}
			}
		}

		.input-bar-textarea {
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 0 20rpx;

			.textarea {
				width: calc(100% - 40rpx);
			}
		}

		.textarea {
			width: calc(100% - 40rpx);
			margin: 0 20rpx;

			.u-textarea {
				width: 100%;
				min-height: 1.1rem;
				max-height: 600rpx;
				overflow-y: scroll;
				background-color: #f5f5f5;
				border-radius: 50rpx;
				padding: 20rpx 40rpx;
				border: none;
				font-size: 28rpx;
				color: #333;
			}
		}

		.btn-list {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
		}

		.submit {
			background-color: $theme-color;
			width: 120rpx;
			height: 60rpx;
			border-radius: 60rpx;
			color: #fff;
			font-size: $font-size-small;
			display: flex;
			justify-content: center;
			align-items: center;

			&:active {
				background-color: $theme-color-dark;
			}
		}
	}

	.operation-bar {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;

		.cell {
			display: flex;
			justify-content: center;
			width: 100%;
			padding: 30rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			font-size: $font-size-base;
			border-bottom: 1px solid #eee;

			/* 评论 */
			&:nth-child(1) {
				color: #666;
				font-size: $font-size-small;
			}

			/* 删除 */
			&:nth-child(4) {
				border-bottom: 10rpx solid #eee;
				color: $uni-color-error;
			}
		}
	}
}
</style>
